# -*- coding: utf-8 -*-
import json
from flask import request, redirect, Flask, jsonify, Response, session
from flask_restful import Resource
from fullstack import app, api, db
from fullstack.Models.member.MemberComments import MemberComments
from fullstack.Models.food.Food import Food
from fullstack.Models.pay.PayOrder import PayOrder
from fullstack.Models.pay.PayOrderItem import PayOrderItem
from fullstack.utils import iPagination, getCurrentTime, MultiEnCoder, paginate
from fullstack.utils import getDictFilterField, selectFilterObj, getDictListFilterField
from sqlalchemy import func

SECTION_URL = '/vue/api/orders'
FLAG=1
STORE=0
COUNT=0

class OrderList(Resource):
    # 监控数据库变化 发现新订单
    def get(self):
        global FLAG,STORE,COUNT
        resp_data = {}
        res = request.values
        pagenum = int(res['pagenum']) if (
            'pagenum' in res and res['pagenum']) else 1
        pagesize = int(res['pagesize']) if (
            'pagesize' in res and res['pagesize']) else 5
        ret = paginate(pagenum, pagesize)
        # 统计记录数量
        total=0 
        # 根据订单编号筛选
        query = PayOrder.query
        if res['order_id']:
            query = query.filter_by(id=int(res['order_id']))
        else:
            # 根据状态筛选
            if res['status']:
                status = int(res['status'])
                # 1=1+0 待评价
                if status == 1:
                    query = query.filter_by(express_status=1, comment_status=0)
                    total=query.count()
                # 2=1+1 已完成
                elif status == 2:
                    query = query.filter_by(express_status=1, comment_status=1)
                    total=query.count()
                # -16=-8-8 待支付
                elif status == -16:
                    query = query.filter_by(express_status=-8, status=-8)
                    total=query.count()
                # -8=-8+0 已关闭
                elif status == -8:
                    query = query.filter_by(express_status=-8, status=0)
                    total=query.count()
                else:
                    query = query.filter_by(express_status=status)
                    total=query.count()
            else:
                # 第一次 FLAG=1
                if FLAG:
                    STORE=query.filter_by(express_status=-7).count()
                    FLAG=0
                COUNT=query.filter_by(express_status=-7).count()
                # 监控数据库变化 发现新订单
                if STORE != COUNT:
                    resp_data['flag']=1
                    STORE=COUNT
                else:
                    resp_data['flag']=0

                query = query.order_by(PayOrder.created_time.desc())
                total=query.count()

        pay_list = query.order_by(PayOrder.id.desc()).offset(
            ret['offset']).limit(ret['limit']).all()
        data_list = []
        if pay_list:
            pay_order_ids = selectFilterObj(pay_list, "id")
            pay_order_items_map = getDictListFilterField(
                PayOrderItem, PayOrderItem.pay_order_id, "pay_order_id", pay_order_ids)

            food_mapping = {}
            if pay_order_items_map:
                food_ids = []
                for item in pay_order_items_map:
                    tmp_food_ids = selectFilterObj(
                        pay_order_items_map[item], "food_id")
                    tmp_food_ids = {}.fromkeys(tmp_food_ids).keys()
                    food_ids = food_ids + list(tmp_food_ids)

                # food_ids里面会有重复的，要去重
                food_mapping = getDictFilterField(
                    Food, Food.id, "id", food_ids)

            for item in pay_list:
                tmp_data = {
                    "id": item.id,
                    "status_desc": item.status_desc,
                    "order_number": item.order_number,
                    "price": str(item.total_price),
                    "pay_time": item.pay_time.strftime('%Y-%m-%d %H:%M:%S'),
                    "created_time": item.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                    "member": json.loads(item.express_info),
                    "note": item.note
                }
                tmp_foods = []
                tmp_order_items = pay_order_items_map[item.id]
                for tmp_order_item in tmp_order_items:
                    tmp_food_info = food_mapping[tmp_order_item.food_id]
                    tmp_foods.append({
                        "name": tmp_food_info.name,
                        "price": str(tmp_order_item.price),
                        "quantity": str(tmp_order_item.quantity),
                    })

                tmp_data['foods'] = tmp_foods
                data_list.append(tmp_data)

        resp_data['list'] = data_list
        resp_data['total']=total
        resp_data['pay_status_mapping'] = app.config['PAY_STATUS_DISPLAY_MAPPING']
        # resp_data['current'] = 'index'

        return resp_data


api.add_resource(OrderList, SECTION_URL+'/list')


# 商家确定收货
class OrderSend(Resource):
    def patch(self):
        res = request.json.get('data')
        id = int(res['id'])
        pay_order = PayOrder.query.filter_by(id=id).first()
        pay_order.express_status = -6
        db.session.add(pay_order)
        db.session.commit()
        resp = {'code': 200, 'status_desc': '待确认'}
        return jsonify(resp)


api.add_resource(OrderSend, SECTION_URL+'/send')

# 用户评价
class OrderComments(Resource):
    def get(self):
        res = request.values
        resp = {'code': 200, 'data': {}}

        # 路由变化时发的空请求
        if 'id' not in res:
            return jsonify(resp)

        id = int(res['id'])
        comment = MemberComments.query.filter_by(pay_order_id=id).first()
        resp['data'] = {
            "score": 0,
            "created_time":"暂无时间",
            'content': "暂无评价"
        }
        if comment:
            resp['data']['score'] = comment.score
            resp['data']['created_time'] = comment.created_time.strftime('%Y-%m-%d %H:%M:%S')
            if comment.content:
                resp['data']['content'] = comment.content
        else:
            resp['data']['content'] = "暂无评价"
            
        return jsonify(resp)


api.add_resource(OrderComments, SECTION_URL+'/comments')

